package org.stone.project.dynamicDataSource.aspect;

import java.util.Objects;
import cn.hutool.core.util.ObjectUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.stone.project.common.pojo.annotation.Ds;
import org.stone.project.dynamicDataSource.utils.DynamicDataSourceContextHolder;

import static org.stone.project.common.pojo.constant.AopExecOrder.DYNAMIC_DS_ORDER;

/**
 * 多数据源处理
 */
@Aspect
@Order(value = DYNAMIC_DS_ORDER)
@Component
public class DataSourceAspect
{
    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Pointcut("@annotation(org.stone.project.common.pojo.annotation.Ds)"
            + "|| @within(org.stone.project.common.pojo.annotation.Ds)")
    public void dsPointCut()
    {

    }

    @Around("dsPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable
    {
        Ds dataSource = getDataSource(point);

        if (ObjectUtil.isNotNull(dataSource))
        {
            DynamicDataSourceContextHolder.setDataSourceType(dataSource.value());
        }

        try
        {
            return point.proceed();
        }
        finally
        {
            // 在执行方法之后，恢复默认数据源
            DynamicDataSourceContextHolder.clearDataSourceType();
        }
    }

    /**
     * 获取需要切换的数据源
     */
    public Ds getDataSource(ProceedingJoinPoint point)
    {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Ds dataSource = AnnotationUtils.findAnnotation(signature.getMethod(), Ds.class);
        if (Objects.nonNull(dataSource))
        {
            return dataSource;
        }

        return AnnotationUtils.findAnnotation(signature.getDeclaringType(), Ds.class);
    }
}
